var express = require("express");
var router = express.Router();

const multiparty = require("multiparty");
const fs = require("fs");
const path = require("path");

router.post("/", function(req, res, next) {
    const form = new multiparty.Form();
    // 设置编码字符集
    form.encoding = "utf-8";
    // 文件储存路径
    form.uploadDir = "./public/images";
    // 设置文件大小限制(2m)
    form.maxFilesSize = 20 * 1024 * 1024;
    // 解析请求
    form.parse(req, function(err, fields, files) {
        console.log("err", err);
        console.log("fields", fields);
        console.log("files", files);
        const { file } = files;
        const avatarpath = file[0].path;
        res.send("http://localhost:3000/images/" + path.parse(avatarpath).base);
    });
});
router.delete("/", function(req, res, next) {
    var {localsrc} = req.body;
    
    localsrc = './public/images/'+path.parse(localsrc).base;
    fs.unlink(localsrc,err=>{
    if(err){
        console.log(err);
    }else{
        res.send(true);
    }
    
    });
});

/* router.get('/download', (req, res) => {
    console.log(req.query);
    const { fileName } = req.query;
    
    fs.readFile(path.join('./public/files', fileName), (err, data) => {
        if (err) {
            console.log("err", err);
            return;
        }
        res.writeHead(200, {
            'Content-Type': 'text/html',
            'Content-Disposition': 'attachment; filename=' + fileName
        });
        res.end(data);
    });
}) */

module.exports = router;
